/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function levelOrder(root: TreeNode | null): number[][] {
    if (!root) {
        return []
    };

    let q: any = [];
    q.push(root);
    const res: any = [];
    let flag = false; // 是否取反标志位

    while (q.length !== 0){
        const len = q.length;
        res.push([]);

        for (let i = 0; i < len; i++){
            const node = q.shift();
            if (flag) {
                res[res.length - 1].unshift(node.val);
            } else {
                res[res.length - 1].push(node.val);
            }
            
            if (node.left) q.push(node.left)
            if (node.right) q.push(node.right);
        }
        flag = !flag;
    }
    return res;
};